package com.fast.common.util;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EncacheUtil {

	private static Logger logger = LoggerFactory.getLogger(EncacheUtil.class);

	private static Cache cache = null;

	static {
		CacheManager cacheMng = CacheManager.create();
		cacheMng.addCache("FastWx");
		cache = cacheMng.getCache("FastWx");
	}

	public static String getCacheKey() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static void remove(String key ){
		cache.remove(key);	
	}
	
	/**
	 * 缓存对象最多保存5分钟
	 * @param key
	 * @param val
	 */
	public static void put(String key, Object val) {
		Element element = new Element(key, val, 24*60 * 60 , 24*60 * 60 );
		if (cache != null) {
			cache.put(element);
		} else {
			logger.error("缓存对象未生成");
		}
	}

	/**
	 * @param key
	 * @param val
	 * @param expireTime 单位为分钟
	 */
	public static void put(String key, Object val , int expireTime ) {
		Element element = new Element(key, val, expireTime * 60, expireTime * 60);
		if (cache != null) {
			cache.put(element);
		} else {
			logger.error("缓存对象未生成");
		}
	}
	
	public static void put(String key, Object val , int idle ,  int tolive) {
		Element element = new Element(key, val, idle * 60, tolive * 60);
		if (cache != null) {
			cache.put(element);
		} else {
			logger.error("缓存对象未生成");
		}
	}
	
	public static <T> T get(String key) {
		if (cache == null) {
			logger.error("缓存对象为空");
			return null;
		}
		if( StringUtils.isEmpty(key)){
			return null;
		}
		Element ele = cache.get(key);
		if( ele == null ){
			return null;
		}
		@SuppressWarnings("unchecked")
		T t = (T) ele.getObjectValue();
		return t;

	}

}
